Python (2nd Edition): Learn Python in One Day and Learn It Well. Python for Beginners with Hands-on Project. (Learn Coding Fast with Hands-On Project Book 1) by Chan Jamie & Publishing LCF
Author:Chan, Jamie & Publishing, LCF
Language: eng
Format: epub, pdf
Publisher: Learn Coding Fast
Published: 2017-05-09T16:00:00+00:00
9.4 Properties
Now that we have a basic understanding of classes and objects, let us move on to discuss properties.
In the examples above, we notice that we can access an object’s instance variables using the dot operator. This makes it easy for us to read the variables and modify them when necessary. However, this flexibility also poses some problems. For instance, we may accidentally change the position of officeStaff1 to a non-existent position. Or we may change the pay of officeStaff1 to an incorrect amount.
To prevent such errors from occurring, we can use properties. Properties provide us with a way to check the values of the changes that we want to make before allowing the change to occur.
To demonstrate how properties work, we’ll add one for the variable position. Specifically, we’ll add a property to ensure that the variable position can only be set to either 'Basic' or 'Manager'.
However, before we do that, we want to first change the name of the instance variable from position to _position. Adding a single underscore in front of a variable name is a customary way to signal to other programmers that they should not touch this variable directly.
In Python programming, there is a commonly used phrase that says "we're all consenting adults here". We are all expected to behave like an adult. Adding a single underscore in front of a variable tells other programmers that you're trusting them to behave responsibly and not access that variable directly unless they have a compelling reason to. However technically, there is nothing stopping them from accessing the variable. If they so desire, they can still access it by writing
officeStaff1._position
Having said that, let’s just make the following changes to the classdemo.py file to let other ‘consenting adults’ know they should not access position directly:
Change the line
self.position = pPosition
in __init__ to
self._position = pPosition
and the line
return "Position = %s, Name = %s, Pay = %d" %(self.position, self.name, self.pay)
in __str__ to
return "Position = %s, Name = %s, Pay = %d" %(self._position, self.name, self.pay)
Next, let’s look at how to add a property for the _position variable:
Add the following lines to the Staff class in classdemo.py.
@property
def position(self):
print("Getter Method")
return self._position
@position.setter
def position(self, value):
if value == 'Manager' or value == 'Basic':
self._position = value
else:
print('Position is invalid. No changes made.')
Remember to indent the lines above when adding them to the Staff class. If you do not indent them, they do not belong to the Staff class.
The first line above (@property) is known as a decorator. We won’t go into details about what a decorator is, but simply put, it allows us to alter the functionality of the method that follows. In this case, it changes the first position() method to a property.
This means that it is telling the compiler that whenever users type
officeStaff1.position
it should use the position() method that follows to get the value.
This method simply prints the message “Getter Method” and returns the value of the variable _position. Due to the @property decorator that changes the method to a property, we do not have to type officeStaff1.position() to access the method.
Download
Python (2nd Edition): Learn Python in One Day and Learn It Well. Python for Beginners with Hands-on Project. (Learn Coding Fast with Hands-On Project Book 1) by Chan Jamie & Publishing LCF.pdf
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.
Eco-friendly approach of bio-indigo synthesis and developing purification methods towards isolation of indigo from indirubin and bacterial fragments by Ramalingam Manivannan & Kaliyan Prabakaran & Young-A Son(151427)
Whisky: Malt Whiskies of Scotland (Collins Little Books) by dominic roskrow(74270)
CONSORT 2025 statement: updated guideline for reporting randomized trials by unknow(66073)
Critical evaluation of the ProfiLER-02 study design and outcomes by Vivek Subbiah & Razelle Kurzrock(65823)
Cardiac gene therapy makes a comeback by Oliver J. Müller & Susanne Hille & Anca Kliesow Remes(65260)
Unveiling the design rules for tunable emission in graphene quantum dots: A high-throughput TDDFT and machine learning perspective by Şener Özönder & Mustafa Coşkun Özdemir & Caner Ünlü(50857)
A yeast-based oral therapeutic delivers immune checkpoint inhibitors to reduce intestinal tumor burden by unknow(35044)
Covalent hitchhikers guide proteins to the nucleus by Alexander F. Russell & Madeline F. Currie & Champak Chatterjee(34988)
Meet the Authors: Christopher R. Mansfield and Emily R. Derbyshire by Christopher R. Mansfield & Emily R. Derbyshire(34714)
What's Done in Darkness by Kayla Perrin(27103)
Topological analysis of non-conjugated ethylene oxide cored dendrimers decorated with tetraphenylethylene: Insights from degree-based descriptors using the polynomial approach by A Theertha Nair & D Antony Xavier & Annmaria Baby & S Akhila(26482)
Investigation of mechanical and self-healing properties of hydroxyl-terminated polybutadiene functionalized with 2-ureido-4-pyrimidinone by Mohsen Kazazi & Mehran Hayaty & Ali Mousaviazar(26435)
The Ultimate Python Exercise Book: 700 Practical Exercises for Beginners with Quiz Questions by Copy(21013)
De Souza H. Master the Age of Artificial Intelligences. The Basic Guide...2024 by Unknown(20774)
D:\Jan\FTP\HOL\Work\Alien Breed - Tower Assault CD32 Alien Breed II - The Horror Continues Manual 1.jpg by PDFCreator(20647)
The Fifty Shades Trilogy & Grey by E L James(19604)
Shot Through the Heart: DI Grace Fisher 2 by Isabelle Grey(19486)
Shot Through the Heart by Mercy Celeste(19345)
Wolf & Parchment: New Theory Spice & Wolf, Vol. 10 by Isuna Hasekura and Jyuu Ayakura(17490)